import 'package:color_dart/RgbaColor.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk_example/provider/moment_model.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:im_flutter_sdk_example/utils/screen.dart';
import 'dart:math';
import 'package:provider/provider.dart';
import 'package:quiver/strings.dart';

class PublishTip extends StatefulWidget {
  PublishTip({Key key}) : super(key: key);

  @override
  _PublishTipState createState() => _PublishTipState();
}

class _PublishTipState extends State<PublishTip> with WidgetsBindingObserver {
  String content = '';
  List<String> pictures = [];
  final picker = ImagePicker();

  KeyboardVisibilityNotification _keyboardVisibility =
      new KeyboardVisibilityNotification();
  int _keyboardVisibilitySubscriberId;
  // bool _keyboardState;

  // 输入框的焦点实例
  FocusNode _focusNode;
  // 当前键盘是否是激活状态
  bool isKeyboardActived = false;

  void setContent(v) {
    print(v);
    content = v;
  }

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    // // 监听输入框焦点变化
    // _focusNode.addListener(_onFocus);
    // // 创建一个界面变化的观察者
    // WidgetsBinding.instance.addObserver(this);
    _registeKeyboardListener();
  }

  _registeKeyboardListener() {
    isKeyboardActived = _keyboardVisibility.isKeyboardVisible;
    _keyboardVisibilitySubscriberId = _keyboardVisibility.addNewListener(
      onChange: (bool visible) {
        setState(() {
          isKeyboardActived = visible;
        });
      },
    );
  }

  int randomNumber() {
    var rng = new Random();
    return rng.nextInt(100000000);
  }

  void onImagePress() async {
    PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
    String path = pickedFile.path;
    DateTime now = DateTime.now();
    FormData formdata = FormData.fromMap(
      {
        "file": await MultipartFile.fromFile(path,
            filename:
                "${now.year}_${now.month}_${now.day}_${randomNumber()}.png"),
        'scene': 'other'
      },
    );
    G.showLoading();
    var res = await G.req.group.upload(file: formdata);
    res.data['data'].forEach((item) {
      pictures.add(item['url']);
    });
    G.dismissLoading();

    setState(() {});
  }

  void publish() {
    if (isNotBlank(content) || pictures?.length != 0) {
      G.showLoading();
      MomentProvider _moment = Provider.of<MomentProvider>(context);
      _moment.publish(content, pictures);
      G.dismissLoading();
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: customAppbar(title: '发布动态', context: context, actions: <Widget>[
        GestureDetector(
          onTap: () => {Navigator.of(context).pop()},
          child: Row(children: [
            Container(
              width: 106.w,
              height: 56.h,
              margin: EdgeInsets.only(right: 32.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2),
                color: rgba(42, 125, 250, 1),
              ),
              child: Center(
                child: InkWell(
                  onTap: () => {publish()},
                  child: Text(
                    '完成',
                    style: TextStyle(
                      color: rgba(255, 255, 255, 1),
                    ),
                  ),
                ),
              ),
            )
          ]),
        )
      ]),
      body: GestureDetector(
        onTap: _keywordDown,
        child: Container(
          color: rgba(255, 255, 255, 1),
          child: Column(
            children: [
              Flexible(
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  child: Column(
                    children: [
                      TextField(
                        autofocus: true,
                        textAlign: TextAlign.start,
                        onChanged: (v) => setContent(v),
                        maxLines: 10,
                        textInputAction: TextInputAction.done,
                        decoration: InputDecoration(
                          border:
                              UnderlineInputBorder(borderSide: BorderSide.none),
                          hintStyle:
                              TextStyle(color: Colors.grey, fontSize: 14),
                          hintText: "记录你此刻的想法…",
                        ),
                        onEditingComplete: _keywordDown,
                      ),
                      SizedBox(
                        width: double.infinity,
                        height: 120,
                        child: GridView.count(
                            crossAxisCount: 3,
                            childAspectRatio: 1.0,
                            crossAxisSpacing: 10,
                            mainAxisSpacing: 12,
                            children: pictures
                                .map((e) => Image.network(e,
                                    width: 90, height: 90, fit: BoxFit.cover))
                                .toList()),
                      ),
                    ],
                  ),
                ),
              ),
              isKeyboardActived == true
                  ? GestureDetector(
                      onTap: onImagePress,
                      child: Container(
                          width: double.infinity,
                          height: 92.h,
                          padding: EdgeInsets.symmetric(horizontal: 40.w),
                          decoration: BoxDecoration(border: G.borderTop()),
                          child: Row(
                            children: [
                              Image.asset("lib/assets/images/alliance/img.png",
                                  fit: BoxFit.cover, width: 42.w, height: 42.w),
                            ],
                          )),
                    )
                  : G.emptyBox()
            ],
          ),
        ),
      ),
    );
  }

  // 既然有监听当然也要有卸载，防止内存泄漏嘛
  @override
  void dispose() {
    super.dispose();
    _focusNode.dispose();
    _keyboardVisibility.removeListener(_keyboardVisibilitySubscriberId);
  }

  _keywordDown() {
    FocusScope.of(context).requestFocus(_focusNode);
  }
}
